﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Protal.Interfaces;
using Microhard.Core.DBUtility;
using Microhard.Protal.DataAccess;
using Microhard.Protal.DTO;
using Microhard.Core;
using Microhard.Protal.Resource;

namespace Microhard.Protal.Impl
{
    public class CategoryImpl : ICategory
    {
        #region IRepository<CategoryModel> Members

        public Core.DBUtility.ExecutedResult Add(Models.CategoryModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrohardProtalEntities db = new MicrohardProtalEntities();
            Microhard_Category op = model.ToEntity();
            op.CreationTime = DateTime.Now;

            try
            {
                db.Microhard_Category.AddObject(op);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add("CategoryImpl.Add", Msg.CategoryImpl_Add);
                Log.Error("CategoryImpl.Add", ex);
            }
            return rtn;
        }

        public Core.DBUtility.ExecutedResult Update(Models.CategoryModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrohardProtalEntities db = new MicrohardProtalEntities();
            Microhard_Category entity = db.Microhard_Category.SingleOrDefault(c => c.CategoryID == model.CategoryID);

            if (entity != null)
            {
                entity.Name = model.Name;
                entity.ParentCategoryID = model.ParentCategoryID;
                entity.CreationTime = DateTime.Now;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add("CategoryImpl.Update", Msg.CategoryImpl_Update);
                Log.Error("CategoryImpl.Update", ex);
            }
            return rtn;
        }

        public Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrohardProtalEntities db = new MicrohardProtalEntities();
            var toDeltes = from b in db.Microhard_Category
                           where ids.Contains(b.CategoryID)
                           select b;
            foreach (var d in toDeltes)
            {
                //是否被使用
                int cnt = db.Microhard_Product.Count(p => p.CategoryID == d.CategoryID);
                if (cnt > 0)
                {
                    result.ErrorMsg.Add("CategoryImpl.IsInUsing", string.Format(Msg.CategoryImpl_IsInUsing, d.Name));
                    continue;

                }
                db.Microhard_Category.DeleteObject(d);
            }
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add("CategoryImpl.Delete", Msg.CategoryImpl_Delete);
                    Log.Error("CategoryImpl.Delete", ex);
                }
            }
            return result;
        }

        public Core.DBUtility.ExecutedResult Delete(Models.CategoryModel model)
        {
            throw new NotImplementedException();
        }

        public Models.CategoryModel GetModelByID(Guid id)
        {
            if (id == Guid.Empty)
                return null;

            MicrohardProtalEntities db = new MicrohardProtalEntities();
            var rtn = db.Microhard_Category.SingleOrDefault(p => p.CategoryID == id);

            if (rtn != null)
                return rtn.ToModel();

            return null;
        }

        public Models.CategoryModel GetModelByModel(Models.CategoryModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.CategoryModel> Query(Models.CategoryModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrohardProtalEntities db = new MicrohardProtalEntities();
            IEnumerable<Microhard_Category> entities = from b in db.Microhard_Category
                                                       where scope.PKID.Contains(b.CategoryID)
                                                       select b;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreationTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            List<Models.CategoryModel> results = new List<Models.CategoryModel>();
            pagedEntities.ForEach(item =>
            {
                var model = item.ToModel();
                if (item.ParentCategoryID != null && item.ParentCategoryID != Guid.Empty)
                {
                    var parItem = db.Microhard_Category.SingleOrDefault(s => s.CategoryID == item.ParentCategoryID.Value);
                    model.ParentCategoryID = parItem.ParentCategoryID;
                    model.ParentCategoryName = parItem.Name;
                }
                results.Add(model);
            });
            return results;
        }

        public List<Models.CategoryModel> Query(Models.CategoryModel Model)
        {
            throw new NotImplementedException();
        }

        public Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }

        #endregion

        #region ICategory Members

        public List<Models.CategoryModel> GetRootCategories(string type)
        {
            MicrohardProtalEntities db = new MicrohardProtalEntities();
            List<Microhard_Category> entities = null;
            if (string.IsNullOrEmpty(type))
            {
                entities = (from c in db.Microhard_Category
                            where c.ParentCategoryID == Guid.Empty
                            select c).ToList();
            }
            else
            {
                entities = (from c in db.Microhard_Category
                            where c.ParentCategoryID == Guid.Empty
                            && c.Name.ToLower() == type.ToLower()
                            select c).ToList();
            }
            List<Models.CategoryModel> results = new List<Models.CategoryModel>();
            entities.ForEach(item =>
            {
                var model = item.ToModel();
                model.Subs = new List<Models.CategoryModel>();
                var subEntities = db.Microhard_Category.Where(s => s.ParentCategoryID == model.CategoryID).ToList();
                if (subEntities.Count > 0)
                {
                    model.Subs = subEntities.Select(e => e.ToModel()).ToList();
                }
                
                results.Add(model);
            });
            return results;
        }

        #endregion
    }
}
